package org.video.mine.mycode;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.view.OrientationEventListener;

public class OrientationListener extends OrientationEventListener {
    public boolean orientationLandscapeLocked = false;
    public boolean orientationPortraitLocked = false;
    private Activity activity;
    private int lastOr = 0;

    public OrientationListener(Context context, Activity activity) {
        super(context);
        this.activity = activity;
    }

    public OrientationListener(Context context, int rate, Activity activity) {
        super(context, rate);
        this.activity = activity;
    }

    @Override
    public void onOrientationChanged(int orientation) {
        int threshold = 4;
        if (Math.abs(orientation - 0) < threshold) orientation = 0;
        else if (Math.abs(orientation - 90) < threshold) orientation = 90;
        else if (Math.abs(orientation - 180) < threshold) orientation = 180;
        else if (Math.abs(orientation - 270) < threshold) orientation = 270;
        if (orientation==lastOr){
            return;
        }
        lastOr = orientation;
        switch (orientation) {
            case 0:
                /*if (!orientationLandscapeLocked) {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    orientationPortraitLocked = false;
                }*/
                break;
            case 90:
                if (!orientationPortraitLocked) {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
                    orientationLandscapeLocked = false;
                }
                break;
            case 180:
                if (!orientationLandscapeLocked) {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
                    orientationPortraitLocked = false;
                }
                break;
            case 270:
                if (!orientationPortraitLocked) {
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    orientationLandscapeLocked = false;
                }
                break;
        }
    }
}
